package sentinel.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
public class Customer8904Controller {
    public static final String SERVER_URL = "http://sentinel-provider-colony";

    @Value("${spring.application.name}")
    private String name;

    @Resource
    private RestTemplate restTemplate;

    /**
     * 不配置sentinel时  ---   接口异常会直接报错，用户体验不好
     */
    @GetMapping("/c1")
    public String c1(){
        return this.name + "-" + restTemplate.getForObject(SERVER_URL + "/c1",String.class);
    }

    /**
     * sentinel  只配置fallback回调函数时（fallback负责业务异常）
     */
    @GetMapping("/c2")
    @SentinelResource(value = "fallback", fallback = "fallbackHandler")
    public String c2(){
        return this.name + "-" + restTemplate.getForObject(SERVER_URL + "/c1",String.class);
    }

    /**
     * sentinel  只配置block回调函数时（block负责sentinel后台配置违规的异常 -- 如配置限流）
     */
    @GetMapping("/c3")
    @SentinelResource(value = "block",blockHandler = "blockHandler")
    public String c3(){
        return this.name + "-" + restTemplate.getForObject(SERVER_URL + "/c1",String.class);
    }

    /**
     * sentinel  配置fallback和block
     */
    @GetMapping("/c4")
    @SentinelResource(value = "blockAndFallback",blockHandler = "blockHandler", fallback = "fallbackHandler")
    public String c4(){
        return this.name + "-" + restTemplate.getForObject(SERVER_URL + "/c1",String.class);
    }

    /**
     * sentinel  配置exceptionsToIgnore
     */
    @GetMapping("/c5")
    @SentinelResource(value = "exceptionsToIgnore",blockHandler = "blockHandler", fallback = "fallbackHandler", exceptionsToIgnore = RuntimeException.class)
    public String c5(){
        if(System.currentTimeMillis() % 2 == 0){
            throw new RuntimeException("这里是RuntimeException异常");
        }
        return this.name + "-" + restTemplate.getForObject(SERVER_URL + "/c1",String.class);
    }

    public String fallbackHandler(Throwable e){
        return "customer-fallback-function";
    }

    public String blockHandler(BlockException blockException){
        return "customer-block-function";
    }
}
